﻿package Utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;

public class SortUtils {
	public static Map.Entry[] sortedHashtableByKey(Hashtable h, int order) {
		Set set = h.entrySet();
		Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
		if (order == Constants.DESC)
			Arrays.sort(entries, new Comparator() {
				public int compare(Object arg0, Object arg1) {
					Object key1 = ((Map.Entry) arg0).getKey();
					Object key2 = ((Map.Entry) arg1).getKey();
					return ((Comparable) key1).compareTo(key2);
				}
			});
		if (order == Constants.ASC)
			Arrays.sort(entries, new Comparator() {
				public int compare(Object arg0, Object arg1) {
					Object key1 = ((Map.Entry) arg0).getKey();
					Object key2 = ((Map.Entry) arg1).getKey();
					return ((Comparable) key2).compareTo(key1);
				}
			});

		return entries;
	}

	public static Map.Entry[] sortedHashtableByValue(Hashtable h, int order) {
		Set set = h.entrySet();
		Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
		if (order == Constants.ASC)
			Arrays.sort(entries, new Comparator() {
				public int compare(Object arg0, Object arg1) {
					Object value1 = ((Map.Entry) arg0).getValue();
					Object value2 = ((Map.Entry) arg1).getValue();
					return ((Comparable) value1).compareTo(value2);
				}
			});
		if (order == Constants.DESC)
			Arrays.sort(entries, new Comparator() {
				public int compare(Object arg0, Object arg1) {
					Object value1 = ((Map.Entry) arg0).getValue();
					Object value2 = ((Map.Entry) arg1).getValue();
					return ((Comparable) value2).compareTo(value1);
				}
			});

		return entries;
	}

	public static void sort(double a[]) {
		double old[] = new double[a.length];
		for (int i = 0; i < old.length; i++)
			old[i] = a[i];

		double temp = 0;
		for (int i = 0; i < a.length - 1; i++) {
			for (int j = 0; j < a.length - i - 1; j++) {
				if (a[j] < a[j + 1]) {
					temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
				}
			}
		}
	}

	public static ArrayList<Integer> sort(ArrayList<Integer> list, int order) {
		for (int i = 0; i < list.size() - 1; i++) {
			for (int j = 1; j < list.size() - i; j++) {
				Integer a;
				if (order == 1) {
					if ((list.get(j - 1)).compareTo(list.get(j)) > 0) { // 比较两个整数的大小

						a = list.get(j - 1);
						list.set((j - 1), list.get(j));
						list.set(j, a);
					}
				} else if (order == -1) {
					if ((list.get(j - 1)).compareTo(list.get(j)) < 0) { // 比较两个整数的大小

						a = list.get(j - 1);
						list.set((j - 1), list.get(j));
						list.set(j, a);
					}
				}
			}
		}
		return list;
	}

}
